/*
 * @Descripttion: 路由工具包
 * @version:
 * @Author: lfzxs@qq.com
 * @Date: 2022-09-26 14:25:41
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2022-09-27 14:21:04
 */
package base

import (
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
)

var (
	RouterKit = routerKit{}
	// 路由链表
	routerList map[string]IRouter
)

func init() {
	routerList = make(map[string]IRouter)
}

// 路由接口
type IRouter interface {
	BindController(group *ghttp.RouterGroup)
}

type routerKit struct {
}

// 获取
func (routerU *routerKit) Get(path string) (IRouter, bool) {
	val, ok := routerList[path]
	return val, ok

}

// func (routerU *routerKit) GetMap() map[string]IRouter {
// 	return routerList
// }

// 安装路由
func (routerU *routerKit) InstallRouter(group *ghttp.RouterGroup) {
	for _, v := range routerList {
		v.BindController(group)
	}
}

// 注册
func (routerU *routerKit) Regist(path string, router IRouter) error {
	_, ok := routerU.Get(path)
	if ok {
		err := gerror.NewCode(gcode.CodeOperationFailed, "路径已存在")

		return err
	}

	routerList[path] = router

	return nil
}

// 注销
func (routerU *routerKit) UnRegist(path string, dict IRouter) error {
	delete(routerList, path)

	return nil
}
